package com.turing.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.turing.entity.User;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * =====>   spring.xml
 */
@Repository
@Configuration
@MapperScan(basePackages = {"com.turing.mapper"})
@ComponentScan(basePackages = {"com.turing"})
public class MyBatisConfig {


	/**
	 * <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">  </bean>
	 *
	 * <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
	 * datasource
	 * mapper文件的路径
	 * 别名
	 *
	 * </bean>
	 * <p>
	 * <mapper-scan basePackage=""/>
	 * SqlSessionFactoryBean   创建的过程会初始化  sqlsession 数据源  事务  mapperProxyFactory
	 * // =====  >    <bean  class="org.mybatis.spring.SqlSessionFactoryBean">
	 */
	@Bean
	public SqlSessionFactoryBean sqlSessionFactory() throws IOException {
		// Spring 集成 MyBatis 实现了 InitializingBean 方法,初始化后 SqlSessionFactoryBean 会调用 afterPropertiesSet
		SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		factoryBean.setDataSource(dataSource());
		// 设置 MyBatis 配置文件路径
		factoryBean.setConfigLocation(new ClassPathResource("mybatis/mybatis-config.xml"));
		// 设置 SQL 映射文件路径
		factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/*.xml"));
		factoryBean.setTypeAliases(User.class);
		return factoryBean;


	}

	/**
	 * MapperScan @import 注册 MapperScannerRegistrar，实现增强，通过替换 FactoryBean 的方式,实现Mapper接口的动态代理
	 */
	public DataSource dataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUsername("root");
		dataSource.setPassword("root");
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://123.57.107.76:3306/test?characterEncoding=utf8");
		return dataSource;
	}

    /*@Bean
	public UserMapper userMapper(){
		return (UserMapper) Proxy.newProxyInstance(UserMapper.class.getClassLoader(), new Class[] { UserMapper.class }, new MyMapperProxy());
	}*/

	/*@Bean("userMapper2")
    public UserMapper userMapper(){sqlSessionFactory
    	return (UserMapper) Proxy.newProxyInstance(UserMapper.class.getClassLoader(), new Class[]{UserMapper.class}, (proxy, method, args1) -> {
			// 查询数据库...   mybatis
			System.out.println("查询");
			return new User();
		});
	}*/
}
